package com.example.hotel.security;
//判断权限
import com.example.hotel.vo.LoginUser;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.access.PermissionEvaluator;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.io.Serializable;
import java.util.Collection;
/**
 * @Author zjy
 * @Date 6-3
 */
@Configuration
public class SecurityPermissionEvaluator implements PermissionEvaluator {
    @Override
    public boolean hasPermission(Authentication authentication, Object targetDomainObject, Object permission) {
        boolean accessible = false;
        if (authentication.getPrincipal() != null) {
            LoginUser loginUser = (LoginUser) authentication.getPrincipal();
            String privilege = targetDomainObject + "_" + permission;
            System.out.println("Privilege " + privilege);

            Collection<? extends GrantedAuthority> authorities = loginUser.getAuthorities();

            for (GrantedAuthority authority: authorities) {
                if (privilege.equalsIgnoreCase(authority.getAuthority())) {
                    accessible = true;
                    break;
                }
            }
        }

        return accessible;
    }

    @Override
    public boolean hasPermission(Authentication authentication, Serializable targetId, String targetType, Object permission) {
        return false;
    }
}
